import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Button } from '@/components/ui/button';
import {
  CaretRightOutlined,
  InboxOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Upload } from 'antd';
import UploadShow from '../Resume/Uploading/UploadShow';
import { evaluateResume } from '@/apis/resume';
const { Dragger } = Upload;

const Hoist: React.FC = () => {
  const [analyseRes, setanalyseRes] = useState('');
  const [JobRes, setJobRes] = useState('');
  const [fileList, setFileList] = useState<
    {
      File: File;
      id: number;
      folderId: string;
    }[]
  >([]);
  const [nowUrl, setNowUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [nowFile, setNowFIle] = useState<any>(null);
  const jobResRef = useRef<HTMLDivElement>(null);
  const analyResRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (jobResRef.current) {
      //   console.log(jobResRef.current);
      // jobResRef.current.scrollIntoView({ behavior: 'smooth' });
      jobResRef.current.scrollTop = jobResRef.current.scrollHeight;
    }
  }, [JobRes]);
  useEffect(() => {
    if (analyResRef.current) {
      //   console.log(analyResRef.current);
      // analyResRef.current.scrollIntoView({ behavior: 'smooth' });

      analyResRef.current.scrollTop = analyResRef.current.scrollHeight;
    }
  }, [analyseRes]);

  const beginEval = async () => {
    if (nowUrl === '') {
      message.error('请先上传简历');
      return;
    }
    setLoading(true);
    const data = {
      resume_url: nowUrl,
    };
    evaluateResume(data).then(async ({ reader, decoder }) => {
      // 循环读取流数据
      let done = false;
      setJobRes('');
      setanalyseRes('');
      while (!done) {
        // 读取流中的一部分
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        if (!done) {
          let buffer = '';
          buffer = decoder.decode(value, { stream: true });
          if (buffer) {
            // parseEventStream(buffer);
            //正则获取{}中间的内容
            const List = buffer.match(/\{(.+?)\}/g) || [];
            // console.log(`"${List[0]}"`);
            if (List[0] && List[0].includes('node_title')) {
              // console.log(123);
              // console.log(List[0]);
              const t = JSON.parse(JSON.parse(`"${List[0]}"`));
              // console.log(JSON.parse(t));
              if (t['node_title'] === '简历评估') {
                setanalyseRes((prev) => prev + t['content']);
                // console.log(t['node_title']);
              } else if (t['node_title'] === '岗位评估') {
                setJobRes((prev) => prev + t['content']);
              }
            }
          }
        }
      }
      setLoading(false);
      // console.log(resText);
    });
  };
  const props: UploadProps = {
    name: 'file',
    multiple: false,
    accept: '.pdf,.doc,.docx', // 限制文件选择类型
    onChange(info) {
      //查看是要删除还是要上传
      if (info.file.status === 'removed') {
        setNowFIle(null);
        return;
      }
      const { type } = info.file;
      console.log(info.file);
      // 限制文件类型为pdf和doc
      if (
        type !== 'application/pdf' &&
        type !== 'application/msword' &&
        type !==
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ) {
        message.error('只能上传PDF和DOC文件');
        return; // 阻止默认上传
      }
      setNowFIle(info.file);
      setFileList([
        {
          File: info.file,
          id: new Date().getTime(),
          folderId: '-1',
        },
      ] as any[]);
      console.log(fileList, info.file.originFileObj);
    },
    beforeUpload: () => {
      return false; // 阻止所有文件的自动上传
    },
    onDrop(e) {
      e.preventDefault(); // 阻止默认上传
    },
    fileList: nowFile ? ([nowFile] as any[]) : [],
  };
  const remove = (id: number) => {
    setFileList((prev) => prev.filter((item) => item.id !== id));
    // console.log(id);
  };
  // const uploadResume: (val, currentId) => {};
  return (
    <>
      <UploadShow files={fileList} remove={remove} reSeturl={setNowUrl} />

      <div className="flex">
        <div className="h-full w-1/2 p-[20px]">
          <Card className="">
            <CardHeader>
              <CardTitle>简历文件</CardTitle>
              <CardDescription>
                请在此处上传您的简历文件（支持pdf与doc）
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Dragger {...props}>
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-hint">点击选择或拖拽上传文件</p>
              </Dragger>
            </CardContent>
          </Card>
          <div className="flex w-full justify-center">
            {' '}
            <Button
              className="mt-[20px]"
              onClick={beginEval}
              disabled={loading}
            >
              {loading ? <LoadingOutlined /> : <CaretRightOutlined />} 开始优化
            </Button>
          </div>
        </div>
        {/* 右侧html */}
        <div className="flex h-[90vh] w-1/2 flex-col p-[20px]">
          <Card className="w-full flex-1">
            <CardHeader>
              <CardTitle>分析结果</CardTitle>
            </CardHeader>
            <CardContent>
              <Card>
                <CardHeader>
                  <CardTitle>简历优化结果</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="max-h-[27vh] overflow-auto" ref={analyResRef}>
                    {' '}
                    <ReactMarkdown remarkPlugins={[remarkGfm]}>
                      {analyseRes}
                    </ReactMarkdown>
                  </div>
                </CardContent>
              </Card>
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  );
};
export default Hoist;
